<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showPercent" :percentage="percent" style="width: 180px" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDNgndDWpML4WdU5yHrADfroAGChwvrnlV', // 身份识别ID
  SecretKey: 'nZQ3VsRlnsb79wTjmZ6Mgu50fLlriHkV' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      // imageUrl: '',
      percent: 0,
      showPercent: false // 默认不显示进度条
    }
  },
  methods: {
    upload (res) {
      if (res.file) {
        // 执行上传操作
        this.showPercent = true
        cos.putObject({
          Bucket: 'liuyuheng-1305723389', /* 存储桶 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => { // 上传进度
            console.log(JSON.stringify(progressData))
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            const imageUrl = `https:${data.Location}`
            // console.log(this.imageUrl)
            this.showPercent = false // 隐藏进度条
            this.$emit('input', imageUrl)
          }
        })
      }
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isPNG = file.type === 'image/png' || 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    position: absolute;
    left: 300px;
    top: -15px;
    font-size: 14px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 60px;
    line-height: 70px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 70px;
    display: block;
  }
</style>
